# coding=utf-8
'''
Created on 2016��11��1��

@author: hhl
'''

import string
import random
import hashlib
import urllib2
import re
from urllib import quote
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

from flask import jsonify
from flask import request,redirect,render_template,make_response
from django.core.cache import cache

from example.worker import api
from example.utils.authclient import authclient
from example.utils.config import MAIN_URL
from example import settings
from example.utils.data_config import *
from example.utils.config import *

            
def encrypt(props):
    """生成加密码
    """ 
    parm_items = sorted(props.items(), key=lambda d: d[0])
    parmlist = ["%s=%s"%item for item in parm_items]
    source_str = "&".join(parmlist)+settings.SECRET_KEY
    sha = hashlib.sha1(source_str)
    return sha.hexdigest().lower()

def check_crypt(props,verification):
    """验证加密码
    """
    return encrypt(props)==verification

def setSecretCookie(response,key,value):
    """设置安全加密cookie
    """
    response.set_cookie(key, value)
    response.set_cookie("%s_sign"%key, encrypt({key:value}))

def getSecretCookie(request,key):
    """获取安全cookie信息
    """
    cookie = request.cookies
    key_value = cookie.get(key)
    sign_key = "%s_sign"%key
    signature = cookie.get(sign_key)
    if check_crypt({key:key_value}, signature):
        return key_value
    return None

def delSecretCookie(response,key):
    """删除cookie
    """
    response.delete_cookie(key)
    response.delete_cookie("%s_sign"%key)

def verify_cookie(func):
    """验证cookie
    """
    def _(*args,**kwargs):
        openid = getSecretCookie(request, "user_openid")
        if openid:
            response = make_response(func(*args,**kwargs))
            setSecretCookie(response, "user_openid", openid)
            return response
        _bkurl = "%s/%s"%(MAIN_URL,request.full_path)
        bkurl = '%s/auth_draw?bkurl=%s'%(MAIN_URL,quote(_bkurl)) #request.url
        redirect_url = authclient.product_auth_url(quote(bkurl),'snsapi_userinfo')
        print 'redirect_url=%s'%redirect_url
        return redirect(redirect_url)
        
    return _

def encrypt_json_token(props,expires_in=ACCESS_TOKEN_EXPIRES):
    """创建TimedJSONWebSignatureSerializer token
    """
    s = Serializer(SECRET_KEY,expires_in=expires_in)
    return s.dumps(props)
    
def decrypt_json_token(token,expires_in=ACCESS_TOKEN_EXPIRES):
    """解析TimedJSONWebSignatureSerializer token的值
    """
    try:
        s = Serializer(SECRET_KEY,expires_in=expires_in)
        token = s.loads(token)
    except:
        token = None
    return token

class add_api_resource:
    """装饰器方法，指定API的资源地址ַ
    """
    
    def __init__(self,*args,**kw):
        """初始化装饰器参数
        """
        self.args = args
        self.kwards = kw
        
    def __call__(self,resource):
        """添加资源到路径中
        """
        api.add_resource(resource,*self.args,**self.kwards)
        return resource
    
    
    
class SignDeal():
    
    def __init__(self):
        pass
    
    def dict_to_url(self,prams):
        parm_items = sorted(prams.items(), key=lambda d: d[0])
        print parm_items
        parmlist = ["%s=%s"%item for item in parm_items]
        print parmlist
        return "&".join(parmlist)
    
    
    def create_sign(self,parms,key):
        parms_str = self.dict_to_url(parms)
        md5_str = '%s&smskey=%s'%(parms_str,key)
        md = hashlib.md5()
        md.update(md5_str)
        sign = md.hexdigest().upper()
        return sign
    
    
    def check_sign(self,parms,key,sign_str):
        create_sign = self.create_sign(parms, key)
        print create_sign
        if create_sign == sign_str:
            return True
        else:
            return False

def produce_access_token(user_id):
    """生成access_token
    """
    data = {"user_id":user_id}
    data["sign"] = encrypt(data)
    access_token = encrypt_json_token(data)
    return access_token

def is_in_weixin():
    """判断是否在微信浏览器
    """
    try:
        pattern = re.compile(r'MicroMessenger', re.I)
        ua = request.headers.get('User-Agent')
        if pattern.search(ua):
            return True
        return False
    except Exception:
        pass
    return False

def is_in_qq_mobile():
    """判断是否在手Q浏览器
    """
    try:
        pattern = re.compile(r'QQ', re.I)
        ua = request.headers.get('User-Agent')
        if pattern.search(ua):
            return True
        return False
    except Exception:
        pass
    return False

def is_in_baidu_mobile():
    """判断是否在手百浏览器
    """
    try:
        pattern = re.compile(r'baiduboxapp', re.I)
        ua = request.headers.get('User-Agent')
        if pattern.search(ua):
            return True
        return False
    except Exception:
        pass
    return False

def is_in_weibo_mobile():
    """判断是否在微博浏览器
    """
    try:
        pattern = re.compile(r'WeiBo', re.I)
        ua = request.headers.get('User-Agent')
        if pattern.search(ua):
            return True
        return False
    except Exception:
        pass
    return False
    
def check_platform():
    """检查网页平台
    """
    if is_in_baidu_mobile():
        return IDENTITY_BAIDU#1
    if is_in_weixin():
        return IDENTITY_WECHAT#2
    if is_in_qq_mobile():
        return IDENTITY_QQ_MOBILE#3
    if is_in_weibo_mobile():
        return IDENTITY_WEIBO#4
    return IDENTITY_NONE#0
    